const request = require("request");
const fs = require("fs");
const shell = require("shelljs");
var colors = require("colors");

let config = require("./config");
/* -------------------------------------------------------------------------- */
main();
async function main() {
  let page = 1;
  while (1) {
    let list = await getRemoteRepositoryList(page);
    if (list.length < 20) {
      await handleList(list, page);
      break;
    }
    await handleList(list, page);
    page++;
  }
}
/* -------------------------------------------------------------------------- */
function recordData(list, page) {
  return new Promise((resolve, reject) => {
    fs.writeFile("list-" + page + ".json", JSON.stringify(list), "utf8", (err) => {
      if (err) {
        reject(err);
      }
      console.log("文件已被保存");
      resolve();
    });
  });
}
async function handleList(list, page) {
  await recordData(list, page);
  var len = list.length;
  for (var i = 0; i < len; i++) {
    let num = page * 20 + i;
    console.log(("" + num).green);
    let item = list[i];
    let ssh_url = item.ssh_url;
    let result = gitClone(ssh_url);
    if (result) {
      await sleep(config.timeInterval);
    } else {
      await sleep(500);
    }
  }
}
function sleep(duration) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, duration);
  });
}
function gitClone(url) {
  console.log("开始下载仓库: " + url);
  let cmd = `git clone ${url}`;
  console.log("cmd: ", cmd);
  let dirPath = config.dirPath;
  shell.cd(dirPath);
  if (shell.exec(cmd).code !== 0) {
    shell.echo("Error: Git commit failed");
    console.log(cmd.red);
    return false;
    // shell.exit(1);
  }
  let baseName = url.split("/").pop();
  console.log(baseName.green);
  console.log("下载仓库成功: " + url + " 到 " + dirPath);
  return true;
}
function getRemoteRepositoryList(page) {
  return new Promise((resolve, reject) => {
    var headers = {
      "Content-Type": "application/json;charset=UTF-8",
    };
    var options = {
      url:
        "https://gitee.com/api/v5/user/repos?access_token=" +
        config.token +
        "&sort=created&page=" +
        page +
        "&per_page=20",
      headers: headers,
    };

    request(options, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        resolve(JSON.parse(body));
      } else {
        reject(error);
      }
    });
  });
}

function createRemoteRepository(projectName) {
  return new Promise((resolve, reject) => {
    var headers = {
      "Content-Type": "application/json;charset=UTF-8",
    };

    var dataString =
      '{"access_token":"' +
      config.token +
      '","name":"' +
      projectName +
      '","has_issues":"true","has_wiki":"true","can_comment":"true","private":"true"}';

    var options = {
      url: "https://gitee.com/api/v5/user/repos",
      method: "POST",
      headers: headers,
      body: dataString,
    };

    request(options, (error, response, body) => {
      if (error) {
        reject(error);
      }
      switch (response.statusCode) {
        case 201:
          console.log("创建远程仓库成功".green, projectName);
          let obj = JSON.parse(body);
          let ssh_url = obj.ssh_url;
          resolve(ssh_url);
          break;
        case 422:
          reject(("已存在同地址仓库（忽略大小写）, 请删除远程仓库, 或者换个项目名字" + projectName).red);
          break;
        default:
          reject("unknown statusCode");
          break;
      }
    });
  });
}
